package org.dreamfly.core.service.impl;

import imageretrievalcopy.ImageContentSearch;
import imageretrievalcopy.MultiThreadSearch;
import imageretrievalcopy.ResultSort;
import org.apache.struts2.ServletActionContext;
import org.dreamfly.core.action.FileActionSupport;
import org.dreamfly.core.bean.SzPicture;
import org.dreamfly.core.bean.SzPictureType;
import org.dreamfly.core.dao.PictureDAO;
import org.dreamfly.core.dao.PictureTypeDAO;
import org.dreamfly.core.page.PageInfo;
import org.dreamfly.core.page.PageResultSet;
import org.dreamfly.core.service.PictureService;
import org.dreamfly.core.util.UrlGetter;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by IntelliJ IDEA.
 * User: Gin
 * Date: 2010-9-16
 * Time: 1:16:44
 * To change this template use File | Settings | File Templates.
 */
public class PictureServiceImpl implements PictureService {
    private PictureDAO pictureDAO;
    private PictureTypeDAO pictureTypeDAO;
    private String applicationPath;
    private String serverName;
    private UrlGetter urlGetter;
    private Lock pictureLock = new ReentrantLock();

    @Override
    public PageResultSet<SzPicture> normalSearch(SzPicture picture, Long pageSize, Long page, String serverName) {
        PageInfo pageInfo = null;
        List<SzPicture> list = null;
        if (serverName == null) {
            pageInfo = new PageInfo(pictureDAO.findCount(SzPicture.class, picture.getTitle()), pageSize, page);
            list = pictureDAO.find(SzPicture.class, picture.getTitle(), Integer.parseInt(pageInfo.getBeginIndex().toString()), Integer.parseInt(pageInfo.getPageSize().toString()), null);
        } else {
            pageInfo = new PageInfo(pictureDAO.findNativeCount(SzPicture.class, picture.getTitle(), serverName), pageSize, page);
            list = pictureDAO.findNative(SzPicture.class, picture.getTitle(), serverName, Integer.parseInt(pageInfo.getBeginIndex().toString()), Integer.parseInt(pageInfo.getPageSize().toString()));
        }
        PageResultSet<SzPicture> pageResultSet = new PageResultSet<SzPicture>();
        pageResultSet.setList(list);
        pageResultSet.setPageInfo(pageInfo);
        return pageResultSet;
    }

    @Override
    public List<SzPicture> test(SzPicture picture, Long pageSize, Long page) {
        PageInfo pageInfo = new PageInfo(pictureDAO.findCount(SzPicture.class, picture.getTitle()), pageSize, page);
        Class<SzPicture> clazz = SzPicture.class;
        List<SzPicture> list = pictureDAO.find(clazz, picture.getTitle(), Integer.parseInt(pageInfo.getBeginIndex().toString()), Integer.parseInt(pageInfo.getPageSize().toString()), null);
        return list;
    }


    public void setPictureDAO(PictureDAO pictureDAO) {
        this.pictureDAO = pictureDAO;
    }

    public void setPictureTypeDAO(PictureTypeDAO pictureTypeDAO) {
        this.pictureTypeDAO = pictureTypeDAO;
    }


    @Override
    public void saveOrUpdate(SzPicture picture) {
        pictureDAO.saveOrUpdate(picture);
    }

    @Override
    public SzPicture findDetail(Long id) {
        SzPicture picture = pictureDAO.find(SzPicture.class, id);
        picture.setPictureUrl(urlGetter.getRemoteUrl(picture.getPictureUrl(), picture.getServer()));
        return picture;
    }

    @Override
    public void delete(Long pictureId) {
        SzPicture picture = pictureDAO.find(SzPicture.class, pictureId);
        String pictureDir = ServletActionContext.getServletContext().getRealPath("") + "\\upload\\" + picture.getPictureUrl().replace("/", "\\");
        String pictureIndexDir = picture.getSzPictureType().getClassIndexUrl();
        pictureLock.lock();
        ImageContentSearch ics = new ImageContentSearch();
        ics.delImageIndex(pictureDir, pictureIndexDir);
        FileActionSupport fas = new FileActionSupport();
        String[] filePaths = {picture.getPictureUrl()};
        fas.setFilePaths(filePaths);
        try {
            fas.delete();
            pictureDAO.delete(picture);
        } catch (Exception e) {
            System.out.println("删除失败");
            e.printStackTrace();
        } finally {
            pictureLock.unlock();
        }
    }

    @Override
    public PageResultSet<SzPicture> findByType(Long pictureTypeId, Long pageSize, Long page) {
        List<Long> pictureTypeIds = new ArrayList<Long>();
        pictureTypeIds.add(pictureTypeId);
        PageInfo pageInfo = new PageInfo(pictureDAO.findCount(pictureTypeIds, "%"), pageSize, page);
        //注意findByType的参数类型
        List<SzPicture> list = pictureDAO.findByType(pictureTypeIds,
                "%",
                Integer.parseInt(pageInfo.getBeginIndex().toString()),
                Integer.parseInt(pageInfo.getPageSize().toString()));
        PageResultSet<SzPicture> pageResultSet = new PageResultSet<SzPicture>();
        pageResultSet.setList(list);
        pageResultSet.setPageInfo(pageInfo);
        pageResultSet.setType("Picture");
        return pageResultSet;
    }

    @Override
    public PageResultSet<SzPicture> normalSearchByType(List<Long> szPictureTypeIds, SzPicture picture, String serverName, Long pageSize, Long page) {
        if (null == szPictureTypeIds) {
            szPictureTypeIds = new ArrayList<Long>();
            List<SzPictureType> types = pictureTypeDAO.findAll(SzPictureType.class);
            for (SzPictureType type : types) {
                szPictureTypeIds.add(type.getTypeId());
            }
        }
        PageInfo pageInfo;
        List<SzPicture> list;
        if (null == serverName) {
            pageInfo = new PageInfo(pictureDAO.findCount(szPictureTypeIds, picture.getTitle()), pageSize, page);
            list = pictureDAO.findByType(szPictureTypeIds,
                    picture.getTitle(),
                    Integer.parseInt(pageInfo.getBeginIndex().toString()),
                    Integer.parseInt(pageInfo.getPageSize().toString()));
        } else {
            pageInfo = new PageInfo(pictureDAO.findNativeCount(szPictureTypeIds, picture.getTitle(), serverName), pageSize, page);
            list = pictureDAO.findNativeByType(szPictureTypeIds,
                    picture.getTitle(),
                    serverName,
                    Integer.parseInt(pageInfo.getBeginIndex().toString()),
                    Integer.parseInt(pageInfo.getPageSize().toString()));
        }
        if (null != list) {
            Iterator iterator = list.iterator();
            while (iterator.hasNext()) {
                SzPicture temp = (SzPicture) iterator.next();
                temp.setTypeName(temp.getSzPictureType().getName());
                temp.setMinPictureUrl(urlGetter.getRemoteUrl(temp.getMinPictureUrl(), temp.getServer()));
            }
        }
        PageResultSet<SzPicture> pageResultSet = new PageResultSet<SzPicture>();
        pageResultSet.setList(list);
        pageResultSet.setPageInfo(pageInfo);
        return pageResultSet;
    }


    @Override
    public List<SzPicture> contentSearchByType(List<Long> szPictureTypeIds
            , String relativePictureDir, Long pageSize, Long page) {
        String pictureDir = applicationPath + relativePictureDir;
        MultiThreadSearch mts = new MultiThreadSearch();
        ArrayList as = new ArrayList();
        List arr;
        List<SzPictureType> result;
        List<String> urls = new ArrayList<String>();
        List<SzPicture> list = new ArrayList<SzPicture>();
        result = new ArrayList<SzPictureType>();
        if (null != szPictureTypeIds && 0 != szPictureTypeIds.size()) {
            for (int i = 0; i < szPictureTypeIds.size(); i++) {
                SzPictureType type = pictureTypeDAO.find(SzPictureType.class, szPictureTypeIds.get(i));
                if (serverName.equals(type.getServer()))
                    result.add(type);
            }
            for (int i = 0; i < result.size(); i++) {
                as.add((result.get(i).getClassIndexUrl()));
            }
        } else {
            result = pictureTypeDAO.findAllByServer(serverName);
            for (int i = 0; i < result.size(); i++) {
                as.add((result.get(i).getClassIndexUrl()));
            }
        }
        //as.add(pictureURL);
        if (0 == as.size()) {
            return null;
        }
        try {
            arr = mts.multiThreadSearch(as, pictureDir);
            long n = (long) arr.size();
            for (int i = 0; i < arr.size(); i++) {
                if (Float.parseFloat(((ResultSort) arr.get(i)).getA()) < 0.1) {
                    n = i;
                    break;
                }
            }
            if (n == 0) {
                return null;
            }
            PageInfo pageInfo = new PageInfo(n, pageSize, page);
            if (page > pageInfo.getTotalPage()) {
                return null;
            }
            for (int i = Integer.parseInt(String.valueOf(pageInfo.getBeginIndex())); i < pageInfo.getBeginIndex() + pageInfo.getPageSize() && i < n; i++) {
                String url = ((ResultSort) arr.get(i)).getC();
                url = url.substring(url.indexOf("picture"));
                url = url.replace("\\", "/");
                SzPicture picture = pictureDAO.findByUrl(url);
                if (null != picture) {
                    //picture.setMinPictureUrl(urlGetter.getRemoteUrl(picture.getMinPictureUrl(), picture.getServer()));
                    picture.setPower(Float.parseFloat(((ResultSort) arr.get(i)).getA()));
                    picture.setTypeName(picture.getSzPictureType().getName());
                    list.add(picture);
                }
            }
            PageResultSet<SzPicture> pageResultSet = new PageResultSet<SzPicture>();
            pageResultSet.setList(list);
            pageResultSet.setPageInfo(pageInfo);
            return list;
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void addPicInfo(SzPicture picture) {
        pictureDAO.saveInfo(picture);
    }

    @Override
    public void modifyPicInfo(SzPicture picture) {
        pictureDAO.modifyInfo(picture);
    }


    @Override
    public List<SzPicture> contentSearch(String pictureDir,
                                         Long pageSize, Long page) {
        MultiThreadSearch mts = new MultiThreadSearch();
        ArrayList as = new ArrayList();
        List arr;
        List<SzPictureType> result;
        List<SzPicture> list = new ArrayList<SzPicture>();
        result = pictureTypeDAO.findAll(SzPictureType.class);
        for (int i = 0; i < result.size(); i++) {
            as.add((result.get(i).getClassIndexUrl()));
        }
        //as.add(pictureURL);
        try {
            arr = mts.multiThreadSearch(as, pictureDir);
            long n = (long) arr.size();
            for (int i = 0; i < arr.size(); i++) {
                Float power = Float.parseFloat(((ResultSort) arr.get(i)).getA());
                if (power < 0.1) {
                    n = i;
                    break;
                }
            }
            if (n == 0L) {
                return new ArrayList<SzPicture>();
            }
            PageInfo pageInfo = new PageInfo(n, pageSize, page);
            for (int i = Integer.parseInt(String.valueOf(pageInfo.getBeginIndex())); i < pageInfo.getBeginIndex() + pageInfo.getPageSize() && i < n; i++) {
                String url = ((ResultSort) arr.get(i)).getC();
                url = url.substring(url.indexOf("picture"));
                url = url.replace("\\", "/");
                SzPicture p = pictureDAO.findByUrl(url);
                if (null != p) {
                    System.out.println(p);
                    list.add(p);
                }
            }
            PageResultSet<SzPicture> pageResultSet = new PageResultSet<SzPicture>();
            pageResultSet.setList(list);
            pageResultSet.setPageInfo(pageInfo);
            return list;
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Long findCount(String pictureDir) {
        MultiThreadSearch mts = new MultiThreadSearch();
        ArrayList as = new ArrayList();
        List arr;
        List<SzPictureType> result;
        List<SzPicture> list = new ArrayList<SzPicture>();
        result = pictureTypeDAO.findAll(SzPictureType.class);
        for (int i = 0; i < result.size(); i++) {
            as.add((result.get(i).getClassIndexUrl()));
        }
        try {
            arr = mts.multiThreadSearch(as, pictureDir);
            long n = (long) arr.size();
            for (int i = 0; i < arr.size(); i++) {
                Float power = Float.parseFloat(((ResultSort) arr.get(i)).getA());
                if (power < 0.1) {
                    n = i;
                    break;
                }
            }
            return n;
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return 0L;
    }

    @Override
    public Long findCount(String relativePictureDir, List<Long> szPictureTypeIds) {
        String pictureDir = applicationPath + relativePictureDir;
        MultiThreadSearch mts = new MultiThreadSearch();
        ArrayList as = new ArrayList();
        List arr;
        List<SzPictureType> result;
        List<String> urls = new ArrayList<String>();
        List<SzPicture> list = new ArrayList<SzPicture>();
        result = new ArrayList<SzPictureType>();
        if (szPictureTypeIds != null && 0 != szPictureTypeIds.size()) {
            for (int i = 0; i < szPictureTypeIds.size(); i++) {
                result.add(pictureTypeDAO.find(SzPictureType.class, szPictureTypeIds.get(i)));
            }
            for (int i = 0; i < result.size(); i++) {
                as.add((result.get(i).getClassIndexUrl()));
            }
        } else {
            result = pictureTypeDAO.findAll(SzPictureType.class);
            for (int i = 0; i < result.size(); i++) {
                as.add((result.get(i).getClassIndexUrl()));
            }
        }

        if (0 == as.size()) {
            return 0L;
        }
        try {
            arr = mts.multiThreadSearch(as, pictureDir);
            long n = (long) arr.size();
            for (int i = 0; i < arr.size(); i++) {
                if (Float.parseFloat(((ResultSort) arr.get(i)).getA()) < 0.1) {
                    n = i;
                    break;
                }
            }
            if (n == 0) {
                return 0L;
            }
            return n;
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return 0L;
    }

    public void setApplicationPath(String applicationPath) {
        this.applicationPath = applicationPath;
    }

    public void setServerName(String serverName) {
        this.serverName = serverName;
    }

    public void setUrlGetter(UrlGetter urlGetter) {
        this.urlGetter = urlGetter;
    }
}
